import Vue from 'vue'
import store from '@/store'

/**
 * Action 权限指令
 * 指令用法：
 *  - 在需要控制 action 级别权限的组件上使用 v-action="'permission'" , 如下：
 *    <i-button v-action="'user:add'" >添加用户</a-button>
 *    <a-button v-action="'user:delete'">删除用户</a-button>
 *    <a v-action="'user:edit'" @click="edit(record)">修改</a>
 *
 *  - 当前用户没有权限时，组件上使用了该指令则会被隐藏
 */
const action = Vue.directive('action', {
    inserted: function (el, binding) {
        console.log('action==>', binding)
        const actionName = binding.value
        const roles = store.getters.roles || []
        let remove = true
        roles.forEach(r => {
            r.permissions.forEach(p => {
                if (p.actions && includeAction(p.actions, actionName)) {
                    remove = false
                }
            })
        })
        if (remove) {
            el.parentNode && el.parentNode.removeChild(el) || (el.style.display = 'none')
        }
    }
})

function includeAction (actions, actionName) {
    for (let i = 0; i < actions.length; i++) {
        if (actions[i].action === actionName) {
            return true
        }
    }
    return false
}

export default action
